package boot.spring.service.impl;

import boot.spring.model.po.TrialClient;
import boot.spring.service.RedisTrailSubscriptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RedisTrailSubscriptionServiceImpl implements RedisTrailSubscriptionService {
    private static final Logger logger = LoggerFactory.getLogger(RedisTrailSubscriptionServiceImpl.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisConnectionFactory connectionFactory;

    private final Map<String, RedisTrailSubscriptionThread> subscriptionThreads = new ConcurrentHashMap<>();


    public RedisTrailSubscriptionServiceImpl() {
    }

    @Override
    public void subscribe(TrialClient trialClient) {
        String sessionId = trialClient.getSessionId();
        if (!subscriptionThreads.containsKey(sessionId)) {
            startSubscriptionThread(trialClient);
        }
    }

    private void startSubscriptionThread(TrialClient trialClient) {
        RedisTrailSubscriptionThread redisTrailSubscriptionThread =
                new RedisTrailSubscriptionThread(trialClient, connectionFactory, redisTemplate);
        redisTrailSubscriptionThread.start();
        subscriptionThreads.put(trialClient.getSessionId(), redisTrailSubscriptionThread);
    }

    @Override
    public void unsubscribe(String sessionId) {
        RedisTrailSubscriptionThread redisTrailSubscriptionThread = subscriptionThreads.get(sessionId);
        if (null != redisTrailSubscriptionThread && redisTrailSubscriptionThread.isAlive()) {
            redisTrailSubscriptionThread.stopThread();
            subscriptionThreads.remove(sessionId);
        }
    }
}